% Analysis script
%% Read from folder
function analyze(guesses_path,input_folder)
load(guesses_path);

radii = zeros(length(guesses),1);
data = zeros(11,2,length(guesses));

for i=1:length(guesses)
    guess_data = guesses{i}.data;
    data(1,:,i) = guess_data(1,1:2);
    radius_iris = guess_data(1,3);
    radii(i) = radius_iris;
    data(2:6,:,i) = guess_data(2:6,1:2);
    data(7:end,:,i) = guess_data(7:end,1:2);
end

%% Get the average radius
average_radius = mean(radii);

%% Rescale and move all the radius back
[~,~,num_of_samples] = size(data);
for i=1:num_of_samples
    datum = data(:,:,i);
    radius = radii(i);
    ratio = double(average_radius)/radius;
    datum = datum * ratio; % Rescale
    
    % Need to translate the coordinate back to the origin
    datum(:,1) = datum(:,1) - datum(1,1);
    datum(:,2) = datum(:,2) - datum(1,2);
    
    data(:,:,i) = datum;
end

%% Average the data points
average_data = sum(data,3)/num_of_samples;

%% Draw the iris
[px, py] = circlepoints(average_radius);

figure(1); plot(px,py,'r','LineWidth',5 ); hold on;
%% %% Sketch final results.
upper_eyelid_normal = average_data(2:6,1:2);
lower_eyelid_normal = average_data(7:end,1:2);
[maxr,~] = size(upper_eyelid_normal);

upper_range_normal = upper_eyelid_normal(1,1):.1:upper_eyelid_normal(maxr,1);
upper_yy_normal = spline(upper_eyelid_normal(:,1),upper_eyelid_normal(:,2),upper_range_normal);

lower_range_normal = lower_eyelid_normal(1,1):.1:lower_eyelid_normal(maxr,1);
lower_yy_normal = spline(lower_eyelid_normal(:,1),lower_eyelid_normal(:,2),lower_range_normal);

upper_dists = zeros(num_of_samples,1);
lower_dists = zeros(num_of_samples,1);
for i=1:num_of_samples
    datum = data(:,:,i);
    upper_eyelid = datum(2:6,1:2);
    lower_eyelid = datum(7:end,1:2);
    
    [maxr,~] = size(upper_eyelid);

    upper_yy = spline(upper_eyelid(:,1),upper_eyelid(:,2),upper_range_normal);
    lower_yy = spline(lower_eyelid(:,1),lower_eyelid(:,2),lower_range_normal);
    
    upper_dists(i) = (sum(((upper_yy - upper_yy_normal)/average_radius).^2))/length(upper_yy);
    lower_dists(i) = (sum(((lower_yy - lower_yy_normal)/average_radius).^2))/length(lower_yy);
    
    plot(upper_range_normal,-upper_yy);
    plot(lower_range_normal,-lower_yy);
end

sd_upper_dists = sqrt(mean(upper_dists));
sd_lower_dists = sqrt(mean(lower_dists));

save(sprintf('%s.normal.mat',input_folder),'lower_eyelid_normal','upper_eyelid_normal','average_radius','sd_upper_dists','sd_lower_dists');

hold on;
plot(upper_range_normal,-upper_yy_normal,'r','LineWidth',5);
plot(lower_range_normal,-lower_yy_normal,'r','LineWidth',5);
axis equal;
% Done
% End of file



